<!-- MySales.vue - 我的销售订单页面 -->
<template>
  <div class="my-sales-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          :icon="ArrowLeft" 
          @click="goBack"
          class="back-button"
        >
          返回
        </el-button>
        <el-icon class="header-icon"><Sell /></el-icon>
        <div>
          <h2 class="header-title">我的销售订单</h2>
          <p class="header-subtitle">共 {{ orders.length }} 个销售订单</p>
        </div>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          :icon="RefreshRight" 
          @click="forceRefresh"
          :loading="loading"
        >
          刷新订单
        </el-button>
      </div>
    </div>

    <!-- 发货提示 -->
    <div class="shipping-tips" v-if="orders.length > 0">
      <el-alert
        title="发货提醒"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <p>当买家下单后，请根据买家提供的收货信息安排发货。发货后请及时更新订单状态，以便买家跟踪物流信息。</p>
        </template>
      </el-alert>
    </div>

    <!-- 状态筛选 -->
    <div class="status-tabs">
      <div 
        class="tab-item" 
        :class="{ active: selectedStatus === null }"
        @click="selectedStatus = null"
      >
        <span class="tab-label">全部</span>
        <span class="tab-count">{{ orders.length }}</span>
      </div>
      <div 
        class="tab-item"
        :class="{ active: selectedStatus === status.value }"
        v-for="status in statusList"
        :key="status.value"
        @click="selectedStatus = status.value"
      >
        <el-icon :class="`icon-${status.type}`">
          <component :is="status.icon" />
        </el-icon>
        <span class="tab-label">{{ status.label }}</span>
        <span class="tab-count">{{ getStatusCount(status.value) }}</span>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="i in 3" :key="i" :rows="3" animated class="loading-card" />
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredOrders.length === 0" class="empty-state">
      <el-empty :description="selectedStatus === null ? '还没有销售订单' : '暂无该状态的订单'">
        <el-button type="primary" @click="$router.push('/gear/selling')">
          去发布商品
        </el-button>
      </el-empty>
    </div>

    <!-- 订单列表 -->
    <div v-else class="orders-list">
      <el-card 
        v-for="order in filteredOrders" 
        :key="order.id"
        class="order-card"
        shadow="hover"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <span class="order-code">订单号：{{ order.code }}</span>
            <span class="order-time">
              <el-icon><Clock /></el-icon>
              {{ formatDate(order.createTime) }}
            </span>
          </div>
          <el-tag :type="getStatusType(order.status)" size="large">
            {{ getStatusText(order.status) }}
          </el-tag>
        </div>

        <!-- 订单内容 -->
        <div class="order-content" @click="viewOrderDetail(order.id)">
          <div class="product-image">
            <el-image :src="getImageUrl(order.coverList)" fit="cover">
              <template #error>
                <div class="image-error">
                  <el-icon><PictureFilled /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <div class="product-info">
            <h3 class="product-name">{{ order.productName }}</h3>
            <p class="product-meta">数量：{{ order.quantity }}</p>
            <div class="product-price">
              <span class="label">实收款：</span>
              <span class="price">¥{{ order.totalAmount }}</span>
            </div>
          </div>

          <div class="buyer-info">
            <p class="buyer-name">
              <el-icon><User /></el-icon>
              买家：{{ order.buyerName }}
            </p>
            <p class="buyer-phone">
              <el-icon><Phone /></el-icon>
              {{ order.buyerPhone }}
            </p>
            <p class="buyer-address">
              <el-icon><Location /></el-icon>
              {{ order.buyerAddress }}
            </p>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button size="small" @click="viewOrderDetail(order.id)">
            订单详情
          </el-button>
          
          <!-- 已支付：可发货 -->
          <template v-if="order.status === 'paid'">
            <el-button size="small" type="primary" @click="handleShipOrder(order)">
              发货
            </el-button>
          </template>

          <!-- 待支付：可取消 -->
          <template v-if="order.status === 'pending'">
            <el-button size="small" type="danger" plain @click="handleCancelOrder(order)">
              取消订单
            </el-button>
          </template>

          <!-- 已发货：等待买家确认 -->
          <template v-if="order.status === 'shipped'">
            <el-button size="small" type="info" plain disabled>
              等待买家确认收货
            </el-button>
          </template>

          <!-- 已完成：交易完成 -->
          <template v-if="order.status === 'delivered'">
            <el-button size="small" type="success" plain disabled>
              交易完成
            </el-button>
          </template>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI, userAPI } from '@/api'
import {
  Sell,
  Clock,
  PictureFilled,
  User,
  Phone,
  Location,
  RefreshRight,
  ArrowLeft
} from '@element-plus/icons-vue'

const router = useRouter()

// 数据
const orders = ref([])
const loading = ref(false)
const selectedStatus = ref(null)

// 状态列表
const statusList = [
  { value: 'pending', label: '待支付', icon: 'Clock', type: 'warning' },
  { value: 'paid', label: '已支付', icon: 'Wallet', type: 'info' },
  { value: 'shipped', label: '已发货', icon: 'Van', type: 'primary' },
  { value: 'delivered', label: '已收货', icon: 'CircleCheck', type: 'success' },
  { value: 'cancelled', label: '已取消', icon: 'WarningFilled', type: 'info' }
]

// 过滤后的订单
const filteredOrders = computed(() => {
  if (selectedStatus.value === null) {
    return orders.value
  }
  return orders.value.filter(order => order.status === selectedStatus.value)
})

// 返回上一页
const goBack = () => {
  // 如果有历史记录，返回上一页，否则返回我的出售页面
  if (window.history.length > 1) {
    router.go(-1)
  } else {
    router.push('/gear/selling')
  }
}

// 强制刷新订单数据
const forceRefresh = async () => {
  console.log('MySales: 强制刷新销售订单数据')
  await fetchSalesOrders()
}

// 获取销售订单列表
const fetchSalesOrders = async () => {
  try {
    loading.value = true
    const response = await orderAPI.getMySales()
    
    if (response.code === 0) {
      orders.value = response.data || []
      console.log('MySales: 获取到的销售订单数据:', orders.value)
      
      // 验证订单数据的完整性
      orders.value = orders.value.filter(order => {
        const isValid = order && order.id && order.status && order.productId
        if (!isValid) {
          console.warn('MySales: 发现无效销售订单，已过滤:', order)
        }
        return isValid
      })
      
      console.log(`MySales: 有效销售订单数量: ${orders.value.length}`)
      
      // 后端已经返回了商品信息，直接使用
      for (const order of orders.value) {
        console.log(`MySales: 订单 ${order.id} 商品信息:`, {
          productName: order.productName,
          price: order.price,
          coverList: order.coverList,
          oldLevel: order.oldLevel
        });
      }
    }
  } catch (error) {
    console.error('获取销售订单失败:', error)
    
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      console.warn('MySales: 用户未授权，可能是token过期')
      // 不显示错误消息，因为request.js已经处理了token清除
      // 用户会被路由守卫重定向到登录页
    } else {
      ElMessage.error('获取销售订单失败')
    }
  } finally {
    loading.value = false
  }
}

// 发货
const handleShipOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确认已发货订单【${order.code}】吗？`,
      '确认发货',
      {
        confirmButtonText: '确认发货',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    console.log('MySales: 开始发货订单:', order.id)
    const response = await orderAPI.shipOrder(order.id)
    console.log('MySales: 发货响应:', response)
    
    if (response.code === 0) {
      ElMessage.success('发货成功')
      order.status = 'shipped'
      
      // 触发全局事件，通知相关页面更新
      window.dispatchEvent(new CustomEvent('orderStatusChanged', {
        detail: { orderId: order.id, status: 'shipped' }
      }))
    } else {
      ElMessage.error(response.message || '发货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发货失败:', error)
      ElMessage.error('发货失败')
    }
  }
}

// 取消订单
const handleCancelOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await orderAPI.cancelOrder(order.id)
    ElMessage.success('订单已取消')
    order.status = 'cancelled'
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/gear/order/${orderId}`)
}

// 工具函数
const getStatusCount = (status) => {
  return orders.value.filter(order => order.status === status).length
}

const getStatusText = (status) => {
  const map = { 
    'pending': '待支付', 
    'paid': '已支付', 
    'shipped': '已发货', 
    'delivered': '已收货', 
    'cancelled': '已取消' 
  }
  return map[status] || '未知'
}

const getStatusType = (status) => {
  const map = { 
    'pending': 'warning', 
    'paid': 'info', 
    'shipped': 'primary', 
    'delivered': 'success', 
    'cancelled': 'info' 
  }
  return map[status] || 'info'
}

const getImageUrl = (coverList) => {
  if (!coverList) return ''
  try {
    const list = typeof coverList === 'string' ? JSON.parse(coverList) : coverList
    return Array.isArray(list) ? list[0] : list
  } catch {
    return coverList
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  fetchSalesOrders()
  
  // 监听订单创建事件，当有订单创建时刷新销售订单列表
  const handleOrderCreated = (event) => {
    console.log('MySales: 检测到订单创建，刷新销售订单列表')
    fetchSalesOrders()
  }
  
  // 监听订单状态变化事件
  const handleOrderStatusChanged = (event) => {
    const { orderId, newStatus } = event.detail
    console.log('MySales: 检测到订单状态变化:', orderId, newStatus)
    fetchSalesOrders()
  }
  
  window.addEventListener('orderCreated', handleOrderCreated)
  window.addEventListener('orderStatusChanged', handleOrderStatusChanged)
  
  // 保存事件处理器引用，用于清理
  window._salesOrderCreatedHandler = handleOrderCreated
  window._salesOrderStatusChangedHandler = handleOrderStatusChanged
})

onUnmounted(() => {
  // 清理事件监听器
  if (window._salesOrderCreatedHandler) {
    window.removeEventListener('orderCreated', window._salesOrderCreatedHandler)
    delete window._salesOrderCreatedHandler
  }
  if (window._salesOrderStatusChangedHandler) {
    window.removeEventListener('orderStatusChanged', window._salesOrderStatusChangedHandler)
    delete window._salesOrderStatusChangedHandler
  }
})
</script>

<style scoped>
.my-sales-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-button {
  color: #409eff;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #f0f9ff;
  color: #337ecc;
}

.shipping-tips {
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
  color: #409eff;
}

.header-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-subtitle {
  margin: 4px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.status-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  padding: 4px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #606266;
}

.tab-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

.tab-item.active {
  background: #409eff;
  color: white;
}

.tab-label {
  font-size: 14px;
  font-weight: 500;
}

.tab-count {
  font-size: 12px;
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 20px;
  text-align: center;
}

.tab-item.active .tab-count {
  background: rgba(255, 255, 255, 0.3);
}

.loading-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.loading-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.order-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-code {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.order-time {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 14px;
}

.order-content {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  cursor: pointer;
  padding: 12px;
  border-radius: 8px;
  transition: background 0.3s ease;
}

.order-content:hover {
  background: #f8f9fa;
}

.product-image {
  flex-shrink: 0;
}

.product-image .el-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  font-size: 24px;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.product-meta {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  color: #909399;
  font-size: 14px;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.buyer-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding-left: 16px;
  border-left: 1px solid #f0f0f0;
}

.buyer-name,
.buyer-phone,
.buyer-address {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.buyer-address {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-sales-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .status-tabs {
    flex-wrap: wrap;
  }
  
  .order-content {
    flex-direction: column;
  }
  
  .buyer-info {
    border-left: none;
    border-top: 1px solid #f0f0f0;
    padding-left: 0;
    padding-top: 12px;
  }
  
  .order-actions {
    flex-wrap: wrap;
  }
}
</style>
